import java.io.InputStream;

import javax.microedition.media.Manager;
import javax.microedition.media.Player;


/**
 * 
 * @author Zheng Hanying
 *
 */
public class MusicPlayerLv2 implements Runnable {
	
	private Thread thread;
	
	private boolean isMusicOn = false;
	
	private boolean isPlaying = false;
	
	private boolean isFail = false;
	
	private Player bgMusicPlayer = null;
	
	public MusicPlayerLv2() {
		try {
			InputStream inputStream = this.getClass().getResourceAsStream("/themeLv2.wav");
			bgMusicPlayer = Manager.createPlayer(inputStream, "audio/x-wav");
			bgMusicPlayer.realize();
		} catch (Exception e) {
			this.isFail = true;
		}
	}
	
	public void run() {
		while (true) {
			try {
				if (this.isPlaying == false) {
					this.bgMusicPlayer.stop();
					break;
				}
				bgMusicPlayer.prefetch();
				bgMusicPlayer.start();
			} catch (Exception e) {
				;
			}
		}
	}
	
	public void setMusicOn(boolean isMusicOn) {
		this.isMusicOn = isMusicOn;
	}
	
	public boolean getIsMusicOn() {
		return this.isMusicOn;
	}

	public void startPlay() {
		if (this.isMusicOn == true && this.isFail == false) {
			this.isPlaying = true;
			try {
				thread = new Thread(this);
				thread.start();
			} catch (Exception e) {
				this.isFail = true;
			}
		}
	}
	
	public void stopPlay() {
		this.isPlaying = false;
		try {
			this.bgMusicPlayer.stop();
		} catch (Exception e) {
			e.printStackTrace();
			this.isFail = true;
		}
	}
}
